
let fs = require('fs')
let async = require('async')
let xlsx = require('node-xlsx')
let AV = require('leanengine');
let moment = require('moment')
var common = require('../cloud/common');


AV.Cloud.define("exchangeMoneyBack",  function (request, response) {
//
    console.log("---11--")
    let query = new AV.Query("Tribe_score");
    query.equalTo('scoreType','EXCHANGE_MONEY')
    query.notEqualTo('type','积分兑换退回')

    query.greaterThanOrEqualTo('createdAt',new Date("2018-09-11 11:02:55"));
    query.find().then(async results=>{

        for (let item of results){
            console.log(item.get("userOId"),"积分兑换退回",-Number(item.get("score")),"EXCHANGE_MONEY")
            await addScoreDetail(item.get("userOId"),"积分兑换退回",-Number(item.get("score")),"EXCHANGE_MONEY")
        }

        console.log(res.length)
    })
//
//
//     // if (score <= userScore) {
//
//     // distributeToken({tokenType: 'TEC', toAddress: request.params.address, amount: rmb}, function (ad) {
//     //     addScoreDetail(request.user.id, keys["SCORE_TYPE"]["EXCHANGE_MONEY"], -score, "EXCHANGE_MONEY");
//     // })
//
//     addScoreDetail(request.user.id, keys["SCORE_TYPE"]["EXCHANGE_MONEY"], -score, "EXCHANGE_MONEY");
//
//
//     // user.set("score",userScore-score);
//     // user.save();
//     // acountDetail(request.user.id,Number(rmb));
//     // userAccount(request.user.id,Number(rmb));
//
//
//     // }
//
//
//
//
})


function addScoreDetail(userId, type, score, scoreType) {
    var TribeScore = common.getEntity("Tribe_score");
    var tribeScore = new TribeScore();
    tribeScore.set("userOId", userId);
    tribeScore.set("type", type);
    tribeScore.set("score", score);
    tribeScore.set("scoreType", scoreType);
    tribeScore.set("userObj", {"__type": "Pointer", className: "_User", objectId: userId});
    return tribeScore.save().then(function (tc) {
        addUserScore(userId, score);

        return tc
    }, function (err) {
        return {};
    })


}

function addUserScore(userId, score) {
    var query = new AV.Query('_User');
    query.equalTo("objectId", userId);
    query.first().then(function (user) {
        if (user) {
            user.increment("score", score);
            user.save().then(u => {
                // apprenticeComp(userId, score);
            });
        }
    }, function (err) {
    })
}